/**
 * 主题管理-主题查询
 */
var querySubjectsSearch = function() {
	var querysubjectFieldSet = new Ext.form.FieldSet({
				id : 'querysubjectFieldSet',
				title : '查询条件',
				collapsible : true,// 可折叠
				buttonAlign : 'center',
				keys : [{
							key : 13, // 13代表回车
							fn : querySubject,
							scope : this
						}],
				items : [{
					layout : 'column',
					border : false,
					items : [{
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											id : "subject_subjectName",
											xtype : 'textfield',
											anchor : '100%',
											fieldLabel : '主题名称',
											name : "subjectName"
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
											xtype : 'dataDictionaryCmb',
											anchor : '100%',
											fieldLabel : "主题状态",
											editable : false,
											autoLoad : false,
											existall : true,
											defaultFirstRow : 1,
											hiddenName : 'subjectStatus',
											dictionaryType : PmsUtil.subject_status
										}]
							}, {
								columnWidth : .25,
								layout : 'form',
								border : false,
								items : [{
									layout : 'column',
									border : false,
									items : [{
												text : '查询',
												xtype : 'button',
												width : 80,
												handler : function() {
													querySubject();
												},
												style : {
													marginLeft : "100px",
													marginRight : "10px"
												}
											}, {
												text : '重置',
												xtype : 'button',
												width : 80,
												handler : function() {
													querySubjectForm.getForm()
															.reset();
												}
											}]
								}]
							}]
				}]
			});
	fieldSetListeners(['querysubjectFieldSet', 'querySubjectForm',
					'subjectManagerGrid'], [0.12, 0.88]);

	var querySubjectForm = new Ext.form.FormPanel({
				id : 'querySubjectForm',
				anchor : '100% 12%',
				frame : true,
				labelAlign : 'right',
				bodyBorder : false,
				items : [querysubjectFieldSet]
			});
	return querySubjectForm;
};

/**
 * grids
 */

var subjectManagerGrid = function() {
	// 定义表的每列（对应表头信息）
	var subjectManagerCm = new Ext.grid.ColumnModel([
			new Ext.grid.RowNumberer(), {
				dataIndex : "id",
				header : "主题编号",
				sortable : true,
				width : 70
			}, {
				dataIndex : "subjectName",
				header : "主题名称",
				sortable : true,
				width : 70,
				renderer : function(value, meta, record) {
					if (value) {
						meta.attr = 'ext:qtitle="主题名称:" ext:qtip="' + value
								+ '"';
						return value;
					}
				}
			}, {
				dataIndex : "subjectPic",
				header : "主题图片",
				sortable : true,
				width : 100,
				renderer : function(value) {
					return PmsUtil.ShowPicture(value);
				}
			}, {
				dataIndex : "subjectOrder",
				header : "主题排序",
				sortable : true,
				width : 70
			}, {
				dataIndex : "subjectStatus",
				header : "主题状态",
				sortable : true,
				width : 70,
				renderer : function(value) {
					return PmsUtil.SubjectStatus(value);
				}
			}, {
				dataIndex : "createdDate",
				header : "创建时间",
				sortable : true,
				width : 130
			}, {
				dataIndex : "createdName",
				header : "创建人",
				sortable : true,
				width : 60
			}, {
				dataIndex : "updatedDate",
				header : "修改时间",
				sortable : true,
				width : 130
			}, {
				dataIndex : "updatedName",
				header : "修改人",
				sortable : true,
				width : 60
			}, {
				header : "管理",
				width : 250,
				dataIndex : "id",
				sortable : false,
				renderer : function(j, i, g, m, h) {
					var subjectId = g.data.id;
					var subjectStatus = g.data.subjectStatus;
					var subjectName = g.data.subjectName;
					var subjectName = g.data.subjectName;
					var subjectStatus = g.data.subjectStatus;
					var k = "";
					if (subjectStatus == 0 && isGranted("subjectManager_发布主题")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="updateSubjectStatus('
								+ subjectId
								+ ','
								+ "1"
								+ ','
								+ "'发布'"
								+ ')\" >发布主题</a>';
					}
					if ((subjectStatus == 0 || subjectStatus == 1)
							&& isGranted("subjectManager_修改主题")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="updateSubject('
								+ subjectId + ')\" >主题修改</a>';
					}
					if (subjectStatus == 1 && isGranted("subjectManager_撤销主题")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="updateSubjectStatus('
								+ subjectId
								+ ','
								+ "2"
								+ ','
								+ "'撤销'"
								+ ')\" >撤销主题</a>';
					}
					if (subjectStatus == 2 && isGranted("subjectManager_取消撤销")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="updateSubjectStatus('
								+ subjectId
								+ ','
								+ "0"
								+ ','
								+ "'取消撤销'"
								+ ');" >取消撤销</a>';
					}
					if (subjectStatus != 2 && isGranted("subjectManager_添加商品")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="addGoodsToSubject('
								+ subjectId
								+ ",'"
								+ subjectName
								+ "')\" >添加商品</a>";
					}
					if (subjectStatus != 2 && isGranted("subjectManager_主题商品")) {
						k += '&nbsp;&nbsp;<a href="#" onclick="selectSubjectGoodsdetail('
								+ subjectId
								+ ')\" >主题商品</a>';
					}
					return k;
				}
			}]);

	// 定义分析器
	var subjectManagerGrid = new Ext.data.JsonReader({
				totalProperty : "totalCount",
				root : "list",
				fields : [{
							name : "id"
						}, {
							name : "subjectName"
						}, {
							name : "subjectPic"
						}, {
							name : "subjectOrder"
						}, {
							name : "subjectStatus"
						}, {
							name : "createdDate"
						}, {
							name : "createdName"
						}, {
							name : "updatedDate"
						}, {
							name : "updatedName"
						}]
			});

	// 取数据store
	var subjectViewStore = new Ext.data.Store({
				autoLoad : true,// 要加载数据必须设置为true
				proxy : new Ext.data.HttpProxy({
							url : __ctxPath + "/subjectManager/selectSubjects"
						}),
				remoteSort : false,
				baseParams : {
					start : 0,
					limit : 25
				},
				listeners : {
					beforeload : {
						fn : function(thiz, options) {
							Ext.apply(thiz.baseParams, Ext
											.getCmp('querySubjectForm')
											.getForm().getValues());
						}
					}
				},
				reader : subjectManagerGrid
			});

	// 定义grid的toolbar
	var subjectTb = new Ext.Toolbar({
				id : "subjectTb",
				height : 28,
				items : []
			});
	subjectTb.add(new Ext.scm.Button({
				text : "主题添加",
				width : 80,
				iconCls : "btn-add",
				pressed : true,
				hsValue : 'subjectManager_新建主题',
				listeners : {
					"click" : function() {
						addSubject();
					}
				}
			}));
	subjectTb.add(new Ext.Toolbar.Spacer());
	subjectTb.add(new Ext.scm.Button({
				text : "刷 新",
				iconCls : "btn-refresh",
				width : 80,
				pressed : true,
				hsValue : 'subjectManager_刷新',
				handler : function() {
					querySubject();
				}
			}));
	
	var subjectManagerGrid = new Ext.grid.GridPanel({
				id : 'subjectManagerGrid',
				store : subjectViewStore,
				cm : subjectManagerCm,
				autoScroll : true,
				loadMask : true,
				stripeRows : true,
				columnLines : true,
				loadMask : {
					msg : "正在加载数据，请稍侯……"
				},
				viewConfig : {
					emptyText : '没有您想要的数据!'
				},
				anchor : '100% 88%',
				frame : true,
				tbar : subjectTb,
				bbar : new PG.PagingBar({
							id : 'subjectGridPage',
							store : subjectViewStore
						})
			});
	return subjectManagerGrid;
};

// 查询
function querySubject() {
	if (Ext.getCmp('querySubjectForm').getForm().isValid()) {
		var grid = Ext.getCmp('subjectManagerGrid');
		var store = grid.store;
		var pagesize = Ext.getCmp('subjectGridPage').pageSize;
		store.load({
					params : {
						start : 0,
						limit : pagesize
					}
				});
	}
}

/**
 * 添加商品
 * 
 * @param {}
 *            subjectId
 */
function addGoodsToSubject(subjectId, subjectName) {
	try {
		addGoodsToSubj(subjectId, subjectName, "添加商品").show();
	} catch (Error) {
		Ext.Loader.load([__ctxPath + '/js/subject/addGoodsForm.js'],
				function() {
					addGoodsToSubj(subjectId, subjectName, "添加商品").show();
				});
	}
}

/**
 * 新建主题
 */
function addSubject() {
	try {
		addOrUpdateSubject(null, "主题添加").show();
	} catch (Error) {
		Ext.Loader.load([__ctxPath + '/js/subject/subjectForm.js'], function() {
					addOrUpdateSubject(null, "主题添加").show();
				});
	}
}
/**
 * 修改主题
 * 
 * @param {}
 *            subjectId
 */
function updateSubject(subjectId) {
	try {
		addOrUpdateSubject(subjectId, "修改主题").show();
	} catch (Error) {
		Ext.Loader.load([__ctxPath + '/js/subject/subjectForm.js'], function() {
					addOrUpdateSubject(subjectId, "修改主题").show();
				});
	}

}
/**
 * 修改主题状态信息
 * 
 * @param {}
 *            subjectId
 * @param {}
 *            status
 * @param {}
 *            message
 */
function updateSubjectStatus(subjectId, status, message) {
	Ext.Msg.confirm("信息确认", "是否" + message + "该条主题信息?", function(c) {
		if (c == "yes") {
			var optionMask = new Ext.LoadMask(Ext.getBody(), {
						msg : "正在处理,请稍后..."
					});
			optionMask.show();
			Ext.Ajax.request({
						url : __ctxPath + "/subjectManager/updateSubjectStatus",
						params : {
							subjectId : subjectId,
							status : status
						},
						method : "post",
						success : function(response) {
							optionMask.hide();
							var jsonData = Ext.util.JSON
									.decode(response.responseText);
							if (jsonData.success) {
								Ext.MessageBox.show({
											title : "信息提示",
											msg : jsonData.data,
											buttons : Ext.MessageBox.OK,
											icon : Ext.MessageBox.INFO
										});
								querySubject();
							} else {
								Ext.MessageBox.show({
											title : "错误提示",
											msg : jsonData.data,
											buttons : Ext.MessageBox.OK,
											icon : Ext.MessageBox.ERROR
										});
							}
						},
						failure : function(response) {
							optionMask.hide();
							Ext.MessageBox.show({
										title : "操作信息",
										msg : "服务器请求异常,请稍后再试!",
										buttons : Ext.MessageBox.OK,
										icon : Ext.MessageBox.ERROR
									});
						}
					});
		}
	});
};
/**
 *主题商品信息
 * @param {} subjectId
 */
function selectSubjectGoodsdetail(subjectId){
	var centerPanel = App.getContentPanel();
	var tab = centerPanel.getItem(PmsUtil.SUBJECT_GOODS_MANAGER_ID);
	var createNewTab = new CreatNewTab(PmsUtil.SUBJECT_GOODS_MANAGER_ID, '主题商品查询');
	if (tab == null) {
		createNewTab.createNew(tab);
	} else {
		createNewTab.createOld(tab, ['querySubGoodsForm',
						'subjectGoodsGrid']);
	}
	Ext.Loader.load([__ctxPath + '/js/subject/subjectGoodsManager.js'], function() {
				Ext.getCmp('subjectGoodsManger_subjectId').setValue(subjectId);
			});
}
Ext.getCmp("centerTabPanel").getActiveTab().add(querySubjectsSearch(),
		subjectManagerGrid());
Ext.getCmp("centerTabPanel").getActiveTab().doLayout();
